package tool;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CreateVersionFile {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(args.length < 3){
			System.err.println("3 args needs [source path] [resource input path] [output path]");
			return;
		}

		String sourceVersion = "";
		// source version
		FileReader fr = null;
		BufferedReader br = null;
		String line = "";
		try {
			fr = new FileReader(args[0]);
			br = new BufferedReader(fr);
			Pattern pattern = Pattern.compile(".+VER *= *(\\d+);");
			while((line = br.readLine()) != null){
				Matcher matcher = pattern.matcher(line);
				if(matcher.matches()){
					sourceVersion = matcher.group(1);
					System.out.println("sourceVersion="+sourceVersion);
					break;
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				br.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		String resourceVersion = "";
		try {
			fr = new FileReader(args[1]);
			br = new BufferedReader(fr);

			resourceVersion = br.readLine();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				br.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				fr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		String version = sourceVersion + resourceVersion;
		int ver = 0;
		try{
			ver = Integer.parseInt(version);
		}catch(NumberFormatException e){
			e.printStackTrace();
			return;
		}
		System.out.println("version=" + ver);

		FileOutputStream fos = null;
		DataOutputStream dos = null;
		try {
			fos = new FileOutputStream(args[2]);
			dos = new DataOutputStream(fos);
			dos.writeChar(ver);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				dos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("version written");

	}

}
